const { Service } = require('egg');
const Response = require('../utils/response');

class UserService extends Service {
  // 注册
  async register(data) {
    const { app } = this;
    const { name, password, email, phone } = data;

    // 检查用户是否已存在
    const existingUser = await app.model.User.findOne({
      where: { name },
    });

    if (existingUser) {
      return Response.error(400, '用户名已存在');
    }

    // 创建新用户
    const user = await app.model.User.create({
      name,
      password,
      email,
      phone,
      status: 1, // 默认启用
      role: 0, // 默认普通用户
    });

    return Response.success({
      id: user.id,
      name: user.name,
      email: user.email,
      phone: user.phone,
    }, '注册成功');
  }

  // 登录
  async login(username, password) {
    const { app } = this;
    const user = await app.model.User.findOne({
      where: { name: username },
    });

    if (!user || user.password !== password) {
      return Response.error(401, '用户名或密码错误');
    }

    if (user.status === 0) {
      return Response.error(403, '用户已禁用');
    }

    const token = app.jwt.sign({
      username: user.name,
      id: user.id,
      role: user.role,
    }, app.config.jwt.secret, { expiresIn: '1d' });

    return Response.success({
      token,
      username: user.name,
      role: user.role,
    });
  }

  // 修改密码
  async changePassword(userId, oldPassword, newPassword) {
    const { app } = this;

    // 查找用户
    const user = await app.model.User.findByPk(userId);
    if (!user) {
      return Response.error(404, '用户不存在');
    }

    // 验证旧密码
    if (user.password !== oldPassword) {
      return Response.error(401, '旧密码错误');
    }

    // 更新密码
    await user.update({ password: newPassword });

    return Response.success(null, '密码修改成功');
  }
}
module.exports = UserService;